package com.knife.tools;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
import java.util.regex.*;
import java.text.*;
public class MyUtil{
    /**
     * 判断一个字符是Ascill字符还是其它字符（如汉，日，韩文字符）
     * 
     * @param char
     *            c, 需要判断的字符
     * @return boolean, 返回true,Ascill字符
     */
    public static boolean isLetter(char c) {
        int k = 0x80;
        return c / k == 0 ? true : false;
    }

    public static boolean IsNum(String s){
    	if(s.equals("")) return(false);
    	String ss = s.replaceAll("[0-9;]+","");
    	if(ss.equals(""))
    		return(true);
    	else
    		return(false);
    }
    /**
     * 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为2,英文字符长度为1
     * 
     * @param String
     *            s ,需要得到长度的字符串
     * @return int, 得到的字符串长度
     */
    public static int length(String s) {
        if (s == null)
            return 0;
        char[] c = s.toCharArray();
        int len = 0;
        for (int i = 0; i < c.length; i++) {
            len++;
            if (!isLetter(c[i])) {
                len++;
            }
        }
        return len;
    }

    /**
     * 截取一段字符的长度,不区分中英文,如果数字不正好，则少取一个字符位
     * 
     * @author patriotlml
     * @param String
     *            origin, 原始字符串
     * @param int
     *            len, 截取长度(一个汉字长度按2算的)
     * @return String, 返回的字符串
     */
    public static String substring(String origin, int len) {
        if (origin == null || origin.equals("")||len<1)
            return "";
        byte[] strByte = new byte[len];
        if (len > MyUtil.length(origin)){
            return origin;}
        System.arraycopy(origin.getBytes(), 0, strByte, 0, len);
        int count = 0;
        for (int i = 0; i < len; i++) {
            int value = (int) strByte[i];
            if (value < 0) {
                count++;
            }
        }
        if (count % 2 != 0) {
            len = (len == 1) ? ++len : --len;
        }
        return new String(strByte, 0, len);
    }
    
    public static String substring(String origin, int len,String morestr) {
        if (origin == null || origin.equals("")||len<1)
            return "";
        byte[] strByte = new byte[len];
        if (len > MyUtil.length(origin)){
            return origin;}
        System.arraycopy(origin.getBytes(), 0, strByte, 0, len);
        int count = 0;
        for (int i = 0; i < len; i++) {
            int value = (int) strByte[i];
            if (value < 0) {
                count++;
            }
        }
        if (count % 2 != 0) {
            len = (len == 1) ? ++len : --len;
        }
        String ns = new String(strByte, 0, len); 
        return(ns + morestr);
    }
    
    /*
     * 防Sql注入过滤
     */
    public static boolean checkSQL(String strSql) throws Exception{    	
    	String inj_str = "'| and |exec|insert |select |delete |update | count|*|%| chr| mid|master |truncate |char |declare |;| or |+";//这里的东西还可以自己添加
    	String[] inj_stra=inj_str.split("\\|");
    	for (int i=0 ; i < inj_stra.length ; i++ ){
    		//System.out.println(inj_stra[i]);
    		if (strSql.indexOf(inj_stra[i])>=0){    			
    			return(true);
    	    }
    	}
    	return(false);
    }
    
    public static String HTMLEncode(String str) throws Exception{
    	try{
    		StringBuffer buf = new StringBuffer();
    	
	        int j = str.length();
	        for(int i = 0; i < j; i++){
	            char c = str.charAt(i);
	            switch(c){
		            case 60: buf.append("&lt;"); break;
		            case 62: buf.append("&gt;"); break;
		            case 38: buf.append("&amp;"); break;
		            case 34: buf.append("&quot;"); break;
		            case 169: buf.append("&copy;"); break;
		            case 174: buf.append("&reg;"); break;
		            case 165: buf.append("&yen;"); break;
		            case 8364: buf.append("&euro;"); break;
		            case 8482: buf.append("&#153;"); break;
		            case 13:
		              if(i < j - 1 && str.charAt(i + 1) == 10){
		            	  buf.append("<br>");
		            	  i++;
		              }
		              break;
		            case 32:
		              if(i < j - 1 && str.charAt(i + 1) == ' '){
		            	  buf.append(" &nbsp;");
		                  i++;
		                  break;
		              }
		            default:
		            	buf.append(c);
		                break;
	            }
	        }
	        return new String(buf.toString());
    	}catch(Exception e){
    		return (str);
    	}
    }
    public static String getFileSize(String url){
    	try{    		
    		String fname = Config.URIMap(url);
    		java.io.File fs = new java.io.File(fname);
    		long flen = fs.length();
    		if(flen<1024)
    			return ( flen + "B");
    		java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
    		double klen = flen /1024f;
    		if(klen <1024)
    			return (df.format(klen) + "KB");
    		double mlen = flen /1024f/1024f;
    		if(mlen <1024)
    			return (df.format(mlen) + "MB");
    		double glen = flen /1024f/1024f/1024f;
    			return (df.format(glen) + "GB");    		
    	}catch(Exception e){
    		return " B";
    	}    	
    }
    public static String getFileSize(long filesize){
    	try{    	
    		java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
    		long flen = filesize;
    		/*
    		if(flen<1024){
    			return ( flen + "B");
    		} 
    		*/   		
    		double klen = flen /1024f;
    		if(klen <1024)
    			return (df.format(klen) + "KB");
    		double mlen = flen /1024f/1024f;
    		if(mlen <1024)
    			return (df.format(mlen) + "MB");
    		double glen = flen /1024f/1024f/1024f;
    			return (df.format(glen) + "GB");    		
    	}catch(Exception e){
    		return " B";
    	}
    }
    public static String getContentSize(String content){
    	try{    	
    		java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
    		int flen = content.length();
    		/*
    		if(flen<1024){
    			return ( flen + "B");
    		} 
    		*/   		
    		double klen = flen /1024f;
    		if(klen <1024)
    			return (df.format(klen) );
    		double mlen = flen /1024f/1024f;
    		if(mlen <1024)
    			return (df.format(mlen));
    		double glen = flen /1024f/1024f/1024f;
    			return (df.format(glen) );    		
    	}catch(Exception e){
    		return " ";
    	}
    }
    public static String getFSize(String fname){
    	//获取文件大小
    	try{
    		java.io.File fs = new java.io.File(fname);
    		long flen = fs.length();
    		if(flen<1024)
    			return ( flen + "B");
    		java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
    		double klen = flen /1024f;
    		if(klen <1024)
    			return (df.format(klen) + "KB");
    		double mlen = flen /1024f/1024f;
    		if(mlen <1024)
    			return (df.format(mlen) + "MB");
    		double glen = flen /1024f/1024f/1024f;
    			return (df.format(glen) + "GB");
    	}catch(Exception ee){
    		return (" B");
    	}
    }
    
    public static String getFileExtName(String fname){
    	int pos;
        pos = fname.lastIndexOf(".");
        if(pos >= 0)
            return(fname.substring(pos + 1));
        else
        	return("");
    }
    public static String getFileName(String fname){
    	String retv = fname;
    	retv = retv.replaceAll("\\\\","/");
    	int pos = retv.lastIndexOf("/");
    	if(pos>=0){
    		retv = retv.substring(pos+1);
    	}else{
    		retv = fname;
    	}
    	return(retv);
    }
    public static HashMap parseEmail(String mail){
    	HashMap map = new HashMap();
    	Pattern p = Pattern.compile("(.+?)<(.+?)>",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);
    	Matcher m = p.matcher(mail);
    	if(m.find()){
    		map.put("name",m.group(1));
    		map.put("email",m.group(2));
    	}else{
    		map.put("name","");
    		map.put("email",mail);
    	}
    	return(map);
    }
    public static String parseEmails(String mails){
    	String mail = "";
    	mails = mails.replaceAll(";",",");
    	mails = mails + ",";
    	Pattern p = Pattern.compile("<(.+?)>",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);
    	String tmp[] = mails.split(",");
    	for(int i=0;i<tmp.length;i++){
    		if(tmp[i].equals("")) continue;
    		if(i>0) mail = mail + ",";
    		Matcher m = p.matcher(tmp[i]);
    		if(m.find()){
    			mail = mail + m.group(1);    			
    		}else{
    			mail = mail + tmp[i];
    		}
    	}
    	return(mail);
    }
    public static String getEmailUser(String email){
    	String user = "";
    	int pos = email.indexOf("@");
    	if(pos>-1){
    		user = email.substring(0,pos);
    	}
    	return(user);
    }
    public static String replace(String strSource, String strFrom, String strTo)
    {
        // 如果要替换的子串为空，则直接返回源串
        if(strFrom == null || strFrom.equals(""))
            return strSource;
        String strDest = "";
        // 要替换的子串长度
        int intFromLen = strFrom.length();
        int intPos;
        // 循环替换字符串
        while((intPos = strSource.indexOf(strFrom)) != -1)
        {
            // 获取匹配字符串的左边子串
            strDest = strDest + strSource.substring(0,intPos);
            // 加上替换后的子串
            strDest = strDest + strTo;
            // 修改源串为匹配子串后的子串
            strSource = strSource.substring(intPos + intFromLen);
        }
        // 加上没有匹配的子串
        strDest = strDest + strSource;
        // 返回
        return(strDest);
    }
    public static String getLZStr(String bianhao,int len){
    	//返回左补零的字符串
		String s = "";
		int l = bianhao.length();
		for(int i=l;i<len;i++)
			s = "0" + s;
		s = s + bianhao;
		return(s);
	}
    
    public static void FileCopyTo(String srcFile,String tarFile) throws Exception{
    	//本地文件拷贝
    	FileInputStream input = new FileInputStream(srcFile);
        FileOutputStream output = new FileOutputStream(tarFile);
        byte[] b = new byte[1024 * 5];
        int len;
        try {
            while ((len = input.read(b)) != -1) {
                output.write(b, 0, len);
            }
        } catch (Exception e) {} 
        finally {
            output.flush();
            output.close();
            input.close();
        }
    }
    public static String formatDate(String sd,String sfmt,String tfmt) {
    	String retv = sd;
    	SimpleDateFormat sdf=new SimpleDateFormat(sfmt);
    	try{
	    	Date date = sdf.parse(sd);
	    	sdf = new SimpleDateFormat(tfmt);
	    	retv = sdf.format(date);
    	}catch(Exception e){
    		retv = sd;
    	}
    	return(retv);
    }
    
    public static String formatDate(Date date,String fmt) {
    	String retv = "";
    	SimpleDateFormat sdf=new SimpleDateFormat(fmt);
    	try{	    	
	    	retv = sdf.format(date);
    	}catch(Exception e){
    		retv = "";
    	}
    	return(retv);
    }
    public static String getDateStr(int year,int month,int day,int flag){
    	String dstr = "";
    	dstr = dstr + year + "-";
    	if(month<10) dstr = dstr + "0";
    	dstr = dstr + month + "-";
    	if(day<10) dstr = dstr + "0";
    	dstr = dstr + day + " ";
    	if(flag==0)
    		dstr = dstr + "00:00:00"; 
    	else if(flag==1)
    		dstr = dstr + "23:59:59";    	
    	return(dstr);
    }
    public static String formatCurrency(String s){
    	String retv = s;    
    	double d = (double)Double.parseDouble(s);
    	NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
    	retv = currencyFormat.format(d);
    	return(retv);
    }
    
    public static String SortString(String s,String c)throws Exception{
    	String tmpstr[]=s.split(c);
    	int tmp[]=new int[tmpstr.length];
    	for(int i=0;i<tmpstr.length;i++)
    		tmp[i] = Integer.parseInt(tmpstr[i]);
    	Arrays.sort(tmp);
    	StringBuffer tmps = new StringBuffer("");
    	for(int i=0;i<tmp.length;i++){
    		if(i>0) tmps.append(",");
    		tmps.append(tmp[i]+"");		
    	}
    	s = tmps.toString();
    	return(s);
    }
    public static String UnicodeStr(String gb2312Str) {   
        String unicoStr = "";   
        if (gb2312Str == null) {   
            gb2312Str = "";   
        }   
        try {   
            byte[] yte = gb2312Str.getBytes("GB2312");   
            unicoStr = new String(yte, "ISO8859_1");   
        } catch (Exception ex) {   
        }   
        return unicoStr;   
    } 
}